package com.amt.configure;

import com.amt.exception.InterfaceParamException;
import com.amt.util.SystemClockUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author 江伟
 * @Title: SystemAspect.java
 * @Package com.amt.configure
 * @Description: TODO(解密验证日志切点)
 * @date 2021年8月1日 下午5:10:27
 * Copyright (c) ©1994-2018 Scjydz.com All Rights Reserved.
 */
@Aspect
@Component
@Slf4j
public class LogAspect {




    /**
     * @param request 请求类
     * @return ip
     * @description: 获取用户ip
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (null == ip || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static String htmlEncode(char c) {
        switch (c) {
//	       case '&':
//	           return "&amp;";
            case '<':
                return "&lt;";
            case '>':
                return "&gt;";
            case '"':
                return "&quot;";
//	       case ' ':
//	           return "&nbsp;";
            default:
                return String.valueOf(c);
        }
    }

    /**
     * @description: 解密验证日志切点
     */
    @Pointcut("@annotation(com.amt.configure.SignatureLog)")
    public void signatureLogAspect() {

    }

    /**
     * @param pjp
     * @return
     * @description: 验证请求参数并解密
     */
    @Around(value = "signatureLogAspect()")
    public Object signatureLog(ProceedingJoinPoint pjp) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取拦截的方法名
        MethodSignature msig = (MethodSignature) pjp.getSignature();
        // 返回被织入增加处理目标对象
        Object target = pjp.getTarget();
        // 为了获取注解信息
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        // 获取注解信息
        SignatureLog annotation = currentMethod.getAnnotation(SignatureLog.class);
        Object[] args = pjp.getArgs();
        Object result = null;
        String requestParam = null;
        StringBuffer sb = new StringBuffer();
        String ip;
        try {
            ip = getIpAddress(request);
            sb.append(target.getClass().getName());
            //解析并设置解密参数内容,如果失败则抛异常
            sb.append(";").append(args[0]).append(";");
            if (null == args[0]) throw new InterfaceParamException("非法的参数内容");
            sb.append(ip).append(";");
            String requestTime = SystemClockUtil.nowDate();
            sb.append(requestTime).append(";");
            result = pjp.proceed(args);
            String responseMessage = result.toString().length() > 30000L ? result.toString().substring(0, 30000) : result.toString();
            sb.append(responseMessage);
            log.info("请求响应数据{}",sb.toString());
//            switch (annotation.signatureType()) {
//                //1his  分别推送到不同的mq队列
//                case "his":
//                    amqpTemplate.convertAndSend("Request","RequestKey",sb);
//                    break;
//                //银海
//                case "yinhai":
//                    amqpTemplate.convertAndSend("Response","ResponseKey",sb);
//                    break;
//                // 社保
//                case "socialSecurity":
//                    amqpTemplate.convertAndSend("socialSecurity","socialSecurityKey",sb);
//                    break;
//                default:
//                    break;
//            }
        } catch (Exception e) {
            log.error("请求参数:{},解密验证异常:{}", args[0], e);
            throw new InterfaceParamException(e);
        }
        return result;
    }

    /**
     * @description: 请求参数转码处理
     */
    private String parseRequestParam(String str) {
        StringBuffer encodeStrBuilder = new StringBuffer();
        for (int i = 0, len = str.length(); i < len; i++) {
            encodeStrBuilder.append(htmlEncode(str.charAt(i)));
        }
        return encodeStrBuilder.toString();
    }

}
